package com.leicx.guli.cart.Interceptor;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.leicx.guli.cart.to.UserInfoTo;
import com.leicx.guli.common.constant.AuthServerConstant;
import com.leicx.guli.common.constant.CartConstant;
import com.leicx.guli.common.vo.MemberResponseVo;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Objects;

/**
 * 判断用户的登录状态
 *
 * @author daxiong
 * @date 2022/8/3 下午3:59
 */
@Component
public class CartInterceptor implements HandlerInterceptor {

    public static ThreadLocal<UserInfoTo> threadLocal = new ThreadLocal<>();

    /**
     * 目标方法执行之前
     *
     * @param request
     * @param response
     * @param handler
     * @return boolean
     * @author daxiong
     * @date 2022/8/3 下午4:00
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HttpSession session = request.getSession();
        MemberResponseVo loginUser = (MemberResponseVo) session.getAttribute(AuthServerConstant.LOGIN_USER);
        UserInfoTo userInfoTo = new UserInfoTo();
        if (Objects.nonNull(loginUser)) {
            // 用户登录过
            userInfoTo.setUserId(loginUser.getId());
        }
        Cookie[] cookies = request.getCookies();
        if (cookies != null && cookies.length > 0) {
            // 获取cookie中保存的user-key
            for (Cookie cookie : cookies) {
                String name = cookie.getName();
                if (Objects.equals(name, CartConstant.TEMP_USER_COOKIE_NAME)) {
                    userInfoTo.setUserKey(cookie.getValue());
                    userInfoTo.setTempUser(true);
                }
            }
        }
        // 如果没有临时user-key，则分配一个
        if (StrUtil.isEmpty(userInfoTo.getUserKey())) {
            userInfoTo.setUserKey(IdUtil.fastSimpleUUID());
        }
        threadLocal.set(userInfoTo);
        return true;
    }

    /**
     * 如果没有临时用户，则分配一个user-key
     *
     * @param request
     * @param response
     * @param handler
     * @param modelAndView
     * @return void
     * @author daxiong
     * @date 2022/8/3 下午5:07
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        UserInfoTo userInfoTo = threadLocal.get();
        if (!userInfoTo.isTempUser()) {
            Cookie cookie = new Cookie(CartConstant.TEMP_USER_COOKIE_NAME, userInfoTo.getUserKey());
            cookie.setDomain("gulimall.com");
            cookie.setMaxAge(CartConstant.TEMP_USER_EXPIRE_TIME);
            response.addCookie(cookie);
        }
    }
}
